package com.dycong.common.common;

import com.dycong.common.json.MyJsonUtil;
import com.dycong.common.network.HttpStatusClient;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Template;
import net.sf.json.JSONObject;
import freemarker.template.Configuration;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dycong on 2017/3/8.
 */
public class SMSTemplate {
    public String getPubMould(String keyName) {

        Map<String, String> header = new HashMap<>();
        Map<String, String> body = new HashMap<>();
        header.put("version", "2");
        int x = 1 + (int) (Math.random() * 500);
        header.put("sequence_id", x + "");
        header.put("appKey"," ClientConfig.omsAppKey");
        header.put("message_type", "PUB_MOULD");
        body.put("mould_key", keyName);
        Map<String, Object> param = new HashMap<>();
        param.put("header", header);
        param.put("body", body);
        String json = MyJsonUtil.toJson(param);

        HttpStatusClient client = new HttpStatusClient();
        long time = System.currentTimeMillis();
        String md5 = StringUtil.getMd5HexByUtf8Encoding(json + "ClientConfig.omsAppCode");
        client.addHeader("signature", md5);
        client.addHeader("appKey", "ClientConfig.omsAppKey");
        client.addHeader("timestamp", time + "");
        String result = client.postJson("ClientConfig.omsBaseUrl "+ "/knocker", json);
        JSONObject resultObject = JSONObject.fromObject(result);
        JSONObject data = resultObject.getJSONObject("body");
        String pubMould = data.getString("pubMould");
        return pubMould;
    }


    public String process(Map param, String templateStr) throws Exception {
        Configuration cfg = new Configuration();
        cfg.setClassicCompatible(true);// 空值处理
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        templateLoader.putTemplate("", templateStr);
        cfg.setTemplateLoader(templateLoader);
        cfg.setDefaultEncoding("UTF-8");
        Template template = cfg.getTemplate("");

        StringWriter writer = new StringWriter();
        template.process(param, writer);
        return writer.toString();
    }

}
